import 'package:flutter/material.dart';

///InheritedWidget
class InheritedPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _InheritedPageState();
  }
}

class _InheritedPageState extends State<InheritedPage> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('InheritedWidget'),
      ),
      body: Center(
        child: SharedDataWidget(
          data: count,
          child: Column(
            children: [
              _TestWidget(),
              OutlineButton(
                child: Text('inherited'),
                onPressed: () {
                  setState(() {
                    count++;
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _TestWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _TestWidgetState();
  }
}

class _TestWidgetState extends State<_TestWidget> {
  @override
  Widget build(BuildContext context) {
    //使用InheritedWidget中的共享数据
    return Text(SharedDataWidget.of(context).data.toString());
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    //父或祖先widget中的InheritedWidget改变(updateShouldNotify返回true)时会被调用。
    //如果build中没有依赖InheritedWidget，则此回调不会被调用。
    print("didChangeDependencies change");
  }
}

class SharedDataWidget extends InheritedWidget {
  dynamic data;

  SharedDataWidget({
    this.data,
    Widget child,
  }) : super(child: child);

  //定义一个便捷方法，方便子树中的widget获取共享数据
  static SharedDataWidget of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<SharedDataWidget>();
  }

  //该回调决定当data发生变化时，是否通知子树中依赖data的Widget
  @override
  bool updateShouldNotify(SharedDataWidget old) {
    //如果返回true，则子树中依赖(build函数中有调用)本widget
    //的子widget的`state.didChangeDependencies`会被调用
    return old.data != data;
  }
}
